﻿'
' Will Strohl (wills@strohlsitedesign.com)
' http://www.willstrohl.com
'
'Copyright (c) 2009, Will Strohl
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are 
'permitted provided that the following conditions are met:
'
'Redistributions of source code must retain the above copyright notice, this list of 
'conditions and the following disclaimer.
'
'Redistributions in binary form must reproduce the above copyright notice, this list 
'of conditions and the following disclaimer in the documentation and/or other 
'materials provided with the distribution.
'
'Neither the name of StrohlSiteDesign.com nor the names of its contributors may be 
'used to endorse or promote products derived from this software without specific prior 
'written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
'TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
'BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
'ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
'DAMAGE.
'

Imports DotNetNuke.Services.Localization
Imports System.IO
Imports System.Text
Imports System.Web.UI
Imports System.Xml

Namespace WillStrohl.Modules.FeedHandler

    ''' <summary>
    ''' FeedRuleTest - this page allows for users to see their rules in action before saving them
    ''' </summary>
    ''' <remarks></remarks>
    ''' <history>
    ''' </history>
    Partial Public Class FeedRuleTest
        Inherits System.Web.UI.Page

#Region " Private Members "

        Private p_FeedId As Integer = Null.NullInteger
        Private p_RuleId As Integer = Null.NullInteger
        Private p_LookFor As String = String.Empty
        Private p_ReplaceWith As String = String.Empty
        Private p_FeedUrl As String = String.Empty
        Private Const c_ResourceFileRoot As String = "~/DesktopModules/WillStrohl.FeedHandler/App_LocalResources/FeedRuleTest.aspx.resx"
        Private Const c_LinkTag As String = "<link rel=""stylesheet"" href=""{0}"" />"

#End Region

#Region " Private Properties "

        ''' <summary>
        ''' FeedId - this property relays the FeedId from the querystring
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private ReadOnly Property FeedId() As Integer
            Get
                If Me.p_FeedId <> Null.NullInteger Then
                    If Not Request.Params("FeedId") Is Nothing Then
                        Me.p_FeedId = Integer.Parse(Request.Params("FeedId").ToString, Globalization.NumberStyles.Integer)
                    End If
                End If

                Return Me.p_FeedId
            End Get
        End Property

        ''' <summary>
        ''' RuleId - this property relays the RuleId from the querystring
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private ReadOnly Property RuleId() As Integer
            Get
                If Me.p_RuleId <> Null.NullInteger Then
                    If Not Request.Params("RuleId") Is Nothing Then
                        Me.p_RuleId = Integer.Parse(Request.Params("RuleId").ToString, Globalization.NumberStyles.Integer)
                    End If
                End If

                Return Me.p_RuleId
            End Get
        End Property

        ''' <summary>
        ''' LookFor - this property relays the LookFor string from the querystring
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private ReadOnly Property LookFor() As String
            Get
                If String.IsNullOrEmpty(Me.p_LookFor) Then
                    If Not Request.Params("LookFor") Is Nothing Then
                        Me.p_LookFor = Request.Params("LookFor").ToString
                    End If
                End If

                Return Me.p_LookFor
            End Get
        End Property

        ''' <summary>
        ''' ReplaceWith - this property relays the ReplaceWith string from the querystring
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private ReadOnly Property ReplaceWith() As String
            Get
                If String.IsNullOrEmpty(Me.p_ReplaceWith) Then
                    If Not Request.Params("ReplaceWith") Is Nothing Then
                        Me.p_ReplaceWith = Request.Params("ReplaceWith").ToString
                    End If
                End If

                Return Me.p_ReplaceWith
            End Get
        End Property

        ''' <summary>
        ''' FeedUrl - this property relays the FeedUrl string from the querystring
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private ReadOnly Property FeedUrl() As String
            Get
                If String.IsNullOrEmpty(Me.p_FeedUrl) Then
                    If Not Request.Params("FeedUrl") Is Nothing Then
                        Me.p_FeedUrl = Server.UrlDecode(Request.Params("FeedUrl").ToString)
                    End If
                End If

                Return Me.p_FeedUrl
            End Get
        End Property

        ''' <summary>
        ''' PortalSettings - this property is used to import a stylesheet
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private ReadOnly Property PortalSettings() As DotNetNuke.Entities.Portals.PortalSettings
            Get
                Return DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings
            End Get
        End Property

#End Region

#Region " Event Handlers "

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Me.BindData()
        End Sub

#End Region

#Region " Private Methods "

        ''' <summary>
        ''' BindData - this method initializes the binding of all controls
        ''' </summary>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private Sub BindData()
            Dim UseFeedIds As Boolean = (Me.FeedId > 0 And Me.RuleId > 0)
            Dim UseFeedText As Boolean = (Not String.IsNullOrEmpty(Me.LookFor) And Not String.IsNullOrEmpty(Me.ReplaceWith) And Not String.IsNullOrEmpty(Me.FeedUrl))
            If UseFeedIds Or UseFeedText Then
                If UseFeedIds Then
                    Dim objFeed As New FeedInfo
                    objFeed = FeedHandlerController.GetFeed(Me.FeedId)
                    Dim objRule As New FeedRuleInfo
                    objRule = FeedHandlerController.GetFeedRule(Me.RuleId)

                    If objFeed Is Nothing Or objRule Is Nothing Then
                        Me.lblMessage.Text = Me.GetLocalizedString("Error.InvalidParams")
                        Exit Sub
                    End If

                    ApplyData(FeedHandlerController.GetDNNRssUrl(objFeed.FeedModuleId), objRule.LookFor, objRule.ReplaceWith)
                ElseIf UseFeedText Then
                    ApplyData(Me.FeedUrl, Me.LookFor, Me.ReplaceWith)
                End If
            Else
                Me.lblMessage.Text = Me.GetLocalizedString("Error.MissingParams")
            End If

            Me.lblOriginalFeed.Text = Me.GetLocalizedString("lblOriginalFeed.Text")
            Me.lblReplacedFeed.Text = Me.GetLocalizedString("lblReplacedFeed.Text")

            Me.Header.Controls.Add(New LiteralControl(String.Format(c_LinkTag, Page.ResolveUrl("~/Portals/_default/default.css"))))
            Me.Header.Controls.Add(New LiteralControl(String.Format(c_LinkTag, Page.ResolveUrl(String.Concat("~/Portals/", Me.PortalSettings.PortalId.ToString, "/portal.css")))))
            Me.Header.Controls.Add(New LiteralControl(String.Format(c_LinkTag, Page.ResolveUrl("~/DesktopModules/WillStrohl.FeedHandler/module.css"))))
        End Sub

        ''' <summary>
        ''' ApplyData - this method is a secondary binding method, called by the BindData method
        ''' </summary>
        ''' <param name="FeedUrl"></param>
        ''' <param name="LookFor"></param>
        ''' <param name="ReplaceWith"></param>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private Sub ApplyData(ByVal FeedUrl As String, ByVal LookFor As String, ByVal ReplaceWith As String)
            Dim strFeed As String = FeedHandlerController.ImportXmlFeed(FeedUrl)
            Me.txtOriginalFeed.Text = Me.IndentXML(strFeed)
            Try
                Me.txtReplacedFeed.Text = Me.IndentXML(FeedHandlerController.ApplyFeedRule(strFeed, LookFor, ReplaceWith))
            Catch ex As Exception
                Me.txtReplacedFeed.Text = String.Concat(Me.GetLocalizedString("Error.RegExExpression"), _
                    Environment.NewLine, Environment.NewLine, ex.Message, Environment.NewLine, Environment.NewLine, ex.StackTrace)
            End Try
        End Sub

        ''' <summary>
        ''' IndentXML - this method returns an indented version of the XML
        ''' </summary>
        ''' <param name="XmlFeed"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private Function IndentXML(ByVal XmlFeed As String) As String
            Dim outXml As String = String.Empty
            Dim ms As MemoryStream = New MemoryStream
            ' Create a XMLTextWriter that will send its output to a memory stream (file)
            Dim xtw As XmlTextWriter = New XmlTextWriter(ms, Encoding.Unicode)
            Dim doc As XmlDocument = New XmlDocument

            ' Load the unformatted XML text string into an instance
            ' of the XML Document Object Model (DOM)
            doc.LoadXml(XmlFeed)

            ' Set the formatting property of the XML Text Writer to indented
            ' the text writer is where the indenting will be performed
            xtw.Formatting = Formatting.Indented

            ' write dom xml to the xmltextwriter
            doc.WriteContentTo(xtw)
            ' Flush the contents of the text writer
            ' to the memory stream, which is simply a memory file
            xtw.Flush()

            ' set to start of the memory stream (file)
            ms.Seek(0, SeekOrigin.Begin)
            ' create a reader to read the contents of
            ' the memory stream (file)
            Dim sr As StreamReader = New StreamReader(ms)
            ' return the formatted string to caller
            Return sr.ReadToEnd()
        End Function

        ''' <summary>
        ''' GetLocalizedString - this method returns the localized value of the resource key/value pair
        ''' </summary>
        ''' <param name="StringKey"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private Function GetLocalizedString(ByVal StringKey As String) As String
            Return Localization.GetString(StringKey, c_ResourceFileRoot)
        End Function

#End Region

    End Class

End Namespace